# -*- coding: utf-8 -*-
import hashlib
import json
from collections import OrderedDict

import requests
from django.conf import settings

from async import async_job
from common.order import db as order_db
from common.order.model import PAY_STATUS
from common.utils import track_logging
from common.utils.exceptions import ParamError

_LOGGER = track_logging.getLogger(__name__)

APP_CONF = {
    '1f8602d43ad0cd512f56f6630825af83': {
        'API_KEY': '05198d59e6428f178f2b539921fd67cecb41ef89',
        'gateway': 'http://haifu.cloudlock.cc:8082/paying/lovepay/getQr',
        'query_gateway': 'http://haifu.cloudlock.cc:8082/paying/lovepay/getPayState',
    },
}


def _get_api_key(mch_id):
    return APP_CONF[mch_id]['API_KEY']


def _get_gateway(mch_id):
    return APP_CONF[mch_id]['gateway']


def _get_query_gateway(mch_id):
    return APP_CONF[mch_id]['query_gateway']


def generate_sign(parameter, key):
    s = ''
    for k in sorted(parameter.keys()):
        s += '%s=%s&' % (k, parameter[k])
    s = s[:len(s) - 1]
    s += key
    m = hashlib.sha1()
    m.update(s.encode('utf8'))
    sign = m.hexdigest().upper()
    return sign


def verify_notify_sign(params, key):
    sign = params['sign']
    params.pop('sign')
    calculated_sign = generate_sign(params, key)
    if sign != calculated_sign:
        _LOGGER.info("haifupay sign: %s, calculated sign: %s", sign, calculated_sign)
        raise ParamError('sign not pass, data: %s' % params)


def _get_device_ip(info):
    try:
        extra = json.loads(info['extra'])
    except:
        extra = {}
    user_info = extra.get('user_info', {})
    return user_info.get('device_ip') or '127.0.0.1'


# 支付类型:
# 0, #微信扫码
# 1, #微信公众号
# 2, #微信 wap
# 3, #支付宝 wap
# 4, #支付宝扫码
# 6, #快捷支付
def _get_pay_type(service):
    if service == 'wxpay':
        payType = '2'
    elif service == 'alipay':
        payType = '3'
    elif service == 'quick':
        payType = '6'
    else:
        payType = '6'
    return payType


def create_charge(pay, pay_amount, info):
    ''' 创建订单 '''
    app_id = info['app_id']
    api_key = _get_api_key(app_id)
    service = info.get('service')

    parameter_dict = OrderedDict((
        ('body', 'charge'),
        ('total_fee', str(int(pay_amount * 100))),
        ('product_id', str(pay.id)),
        ('goods_tag', '234'),
        ('op_user_id', app_id),
        ('nonce_str', '234234234'),
        ('spbill_create_ip', _get_device_ip(info)),
        ('notify_url', '{}/pay/api/{}/haifupay/{}'.format(settings.NOTIFY_PREFIX, settings.NOTIFY_PATH, app_id)),
        ('front_notify_url', '{}/pay/api/{}/haifupay/{}/'.format(settings.NOTIFY_PREFIX, settings.RETURN_PATH, pay.id)),
        ('pay_type', _get_pay_type(service)),
    ))

    parameter_dict['sign'] = generate_sign(parameter_dict, api_key)
    j = json.dumps(parameter_dict)
    _LOGGER.info("haifupay create data: %s", j)
    headers = {'Content-Type': 'application/json; charset=utf-8'}
    response = requests.post(_get_gateway(app_id), data=j, headers=headers, timeout=10)
    _LOGGER.info("haifupay create rsp data: %s %s", response.status_code, response.text)
    j = json.loads(response.text)
    return {'charge_info': j[u'code_url']}


def check_notify_sign(request, app_id):
    api_key = _get_api_key(app_id)
    _LOGGER.info("haifupay notify body: %s", request.body)
    data = json.loads(request.body)
    verify_notify_sign(data, api_key)
    pay_id = data['productId']
    if not pay_id:
        _LOGGER.error("fatal error, out_trade_no not exists, data: %s" % data)
        raise ParamError('haifupay event does not contain pay ID')

    pay = order_db.get_pay(int(pay_id))
    if not pay:
        raise ParamError('pay_id: %s invalid' % pay_id)
    if pay.status != PAY_STATUS.READY:
        raise ParamError('pay %s has been processed' % pay_id)

    mch_id = pay.mch_id
    trade_status = str(data['state'])
    trade_no = data['tradeNum']
    total_fee = float(data['fee']) / 100.0

    extend = {
        'trade_status': trade_status,
        'trade_no': trade_no,
        'total_fee': total_fee
    }

    from common.channel.pay import check_channel_order
    check_channel_order(pay_id, total_fee, app_id)

    if trade_status == '1':
        _LOGGER.info('haifupay check order success, mch_id:%s pay_id:%s' % (mch_id, pay_id))
        order_db.add_pay_success(mch_id, pay_id, total_fee, trade_no, extend)
        # async notify
        async_job.notify_mch(pay_id)

    res = {
        "errcode": 200,
        'info': 'success',
        'tradeNum': data['tradeNum'],
        'notifyUrl': '{}/pay/api/{}/haifupay/{}'.format(settings.NOTIFY_PREFIX, settings.NOTIFY_PATH, app_id),
    }
    res['sign'] = generate_sign(res, api_key)
    return json.dumps(res)


def query_charge(pay_order, app_id):
    ''' 查询订单 '''
    # prepare param
    pay_id = pay_order.id
    order_id = str(pay_id)
    api_key = _get_api_key(app_id)
    parameter_dict = OrderedDict((
        ('opUserId', app_id),
        ('productId', str(order_id)),
    ))
    parameter_dict['sign'] = generate_sign(parameter_dict, api_key)
    j = json.dumps(parameter_dict)
    _LOGGER.info("haifupay query data: %s", j)
    headers = {'Content-Type': 'application/json; charset=utf-8'}
    response = requests.post(_get_query_gateway(app_id), data=j, headers=headers, timeout=10)
    _LOGGER.info('haifupay query rsp :%s', response.text)
    if response.status_code == 200:
        data = json.loads(response.text)
        trade_status = str(data['state'])
        trade_no = data['tradeNum']
        total_fee = float(pay_order.total_fee)

        extend = {
            'trade_status': trade_status,
            'trade_no': trade_no,
            'total_fee': total_fee
        }

        # 0:未支付;
        # 1:支付成功;
        # 2:支付失败
        if trade_status == '1':
            _LOGGER.info('haifupay query order success, user_id:%s pay_id:%s' % (pay_order.mch_id, pay_id))
            order_db.add_pay_success(pay_order.mch_id, pay_order.id,
                                     total_fee, trade_no, extend)
            async_job.notify_mch(pay_order.id)
    else:
        _LOGGER.warn('haifupay data error, status_code: %s', response.status_code)
